<?php
namespace app\admin\controller;
use app\common\controller\AdminController;
use think\facade\Cache;
use think\facade\View;

use think\facade\Db;
use clt\Leftnav;
use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\AuthStanding;
use app\admin\model\authRule;
use think\Model;

class Auth extends AdminController
{
    //管理员列表
    public function adminList(){
        if($this->request->isAjax()){
            $val=input('val');
            $url['val'] = $val;
            View::assign('testval',$val);
            $map='';
            if($val){
                $map['username|email|tel']= ['like',"%".$val."%"];
            }
            if ($this->admin['admin_id']!=1){
                $map='admin_id='.$this->admin['admin_id'];
            }
            $list=Db::table(config('database.connections.mysql.prefix').'admin')->alias('a')
                ->join(config('database.connections.mysql.prefix').'auth_group ag','a.group_id = ag.id','left')
                ->join(config('database.connections.mysql.prefix').'auth_standing as','a.standing = as.key','left')
                ->field('a.*,ag.title,as.name as standing')
                ->where($map)
                ->select();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1]);
        }
        return view();
    }

    public function adminAdd(){
        if($this->request->isAjax()){
            $data = $this->request->post();
            $admin_id = Admin::where(['username'=>$data['username']])->value('admin_id');
            if ($admin_id) {
                $this->error('用户已存在，请重新输入用户名!');
            }
            $data['pwd'] = input('post.pwd', '','trim');
            $data['add_time'] = time();
            $data['ip'] = $this->request->ip();
            //验证
    try {
                validate('app\admin\validate\Admin')->check($data);
            } catch (\think\exception\ValidateException $e) {
                // 验证失败 输出错误信息
                $this->error($e->getError());
            }

            if (empty($data['pwd'])) {
                $this->error('密码不能为空！');
            }
            $data['pwd']=md5($data['pwd'].'QQ1147361223');
            //添加
            if (Admin::create($data)) {
                $this->success('管理员添加成功!',myurl('adminList'));
            } else {
                $this->error('管理员添加失败!');

            }
        }else{
            $this->app->view->engine()->layout(false);
            $auth_standing = AuthStanding::field('key,name')->select()->toArray();
            $auth_standing_list = [];
            foreach ($auth_standing as $v) {
                $auth_standing_list[$v['key']] = $v['name'];
            }
            View::assign('AuthStandingList',$auth_standing_list);
            $auth_group = AuthGroup::select()->toArray();
            View::assign('authGroup',$auth_group);
            View::assign('title',lang('add').lang('admin'));
            View::assign('info','null');
            View::assign('info_raw',[]);
            View::assign('selected', 'null');
            return view('adminForm');
        }
    }
    //删除管理员
    public function adminDel(){
        $admin_id=input('get.admin_id');
        if($admin_id==1){
            return json(['code'=>0,'msg'=>'超级管理员账号禁止删除!']);
        }
        if ($this->admin['admin_id']==1){
            Admin::where('admin_id','=',$admin_id)->delete();
            return json(['code'=>1,'msg'=>'删除成功!']);
        }else{
            return json(['code'=>0,'msg'=>'您没有删除员工账号的权限!']);
        }
    }
    //修改管理员状态
    public function adminState(){
        $id=input('post.id');
        $is_open=input('post.is_open');
        if (empty($id)){
            $result['status'] = 0;
            $result['info'] = '用户ID不存在!';
            $result['url'] = myurl('adminList');
            return json($result);
        }
        \think\facade\Db::name('admin')->where('admin_id='.$id)->update(['is_open'=>$is_open]);
        $result['status'] = 1;
        $result['info'] = '用户状态修改成功!';
        $result['url'] = myurl('adminList');
        return json($result);
    }
    //设置是否查看手机号
    public function adminPhone(){

        $id=input('post.id');
        $isphone=input('post.isphone');
        if (empty($id)){
            $result['status'] = 0;
            $result['info'] = '用户ID不存在!';
            $result['url'] = myurl('adminList');
            return json($result);
        }
        \think\facade\Db::name('admin')->where('admin_id='.$id)->update(['isphone'=>$isphone]);
        $result['status'] = 1;
        $result['info'] = '用户权限修改成功!';
        $result['url'] = myurl('adminList');
        return json($result);
    }
    # 设置是否轮询
    public function adminPoll(){
        $id=input('post.id');
        $is_poll=input('post.is_poll');
        if (empty($id)){
            $result['status'] = 0;
            $result['info'] = '用户ID不存在!';
            $result['url'] = myurl('adminList');
            return json($result);
        }
        \think\facade\Db::name('admin')->where('admin_id='.$id)->update(['is_poll'=>$is_poll]);
        $result['status'] = 1;
        $result['info'] = '用户状态修改成功!';
        $result['url'] = myurl('adminList');
        return json($result);
    }
    //更新管理员信息
    public function adminEdit(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $pwd=input('post.pwd');
            $map[] = ['admin_id','<>',$data['admin_id']];
            $where['admin_id'] = $data['admin_id'];

            if($data['username']){
                $map[] = ['username','=',$data['username']];
                $check_user = Admin::where($map)->find();
                if ($check_user) {
                    return json(['code'=>0,'msg'=>'用户已存在，请重新输入用户名!']);
                }
            }
            if ($pwd){
                $data['pwd']=input('post.pwd','');
                $data['pwd']=md5($data['pwd'].'QQ1147361223');
            }else{
                unset($data['pwd']);
            }
          /*  $msg = $this->validate($data,'app\admin\validate\Admin');
            if($msg!='true'){
                return json(['code'=>0,'msg'=>$msg]);
            }*/
            try {
                validate('app\admin\validate\Admin')->check($data);
            } catch (\think\exception\ValidateException $e) {
                // 验证失败 输出错误信息
                $this->error($e->getError());
            }
            $data['standing'] = implode(',', $data['standing_list']);
            unset($data['standing_list']);
            $model=Admin::update($data,$where);

            if( $data['admin_id'] == $this->admin['admin_id']){
                $admin=Db::name('admin')->withoutField('pwd')->where('admin_id', '=',$this->admin['admin_id'])->find();
                session('admin',$admin);
            }
            return json(['code'=>1,'msg'=>'管理员修改成功!','url'=>myurl('adminList')]);
        }else{

            $admin = new Admin();
            $info = $admin->getInfo(input('admin_id'));
            $info['standing_list'] = explode(',', $info['standing']);
            View::assign('info', json_encode($info,true));
            View::assign('info_raw', $info);
            View::assign('title',lang('edit').lang('admin'));
            $this->app->view->engine()->layout(false);

            $auth_standing = AuthStanding::field('key,name')->select()->toArray();
            $auth_standing_list = [];
            foreach ($auth_standing as $v) {
                $auth_standing_list[$v['key']] = $v['name'];
            }
            View::assign('AuthStandingList',$auth_standing_list);
            return view('adminForm');
        }
    }

    //更新管理员提成设置
    public function adminSetticheng(){

        if($this->request->isAjax()) {
            $datas = $this->request->post();
            $configs = [];
            if (!empty($datas['config'])) {
                //多规则格式转换，核验
                if (!is_array($datas['config'])) {
                    return json(['code' => 0, 'msg' => '规则格式有误']);
                }
                foreach ($datas['config'] as $k => $config) {
                    if (empty($config['num'])) {
                        return json(['code' => 0, 'msg' => '提成点不可为空/0']);
                    }
                    if (empty($config['start_money']) && empty($config['end_money'])) {
                        return json(['code' => 0, 'msg' => '区间起至不可为空']);
                    }
                    if (!empty($config['start_money']) && !empty($config['end_money'])) {
                        if ($config['start_money'] >= $config['end_money']) {
                            return json(['code' => 0, 'msg' => '起始金额'.$config['start_money']."不得大于结束金额"]);
                        }
                    }

                    if(!empty($configs)) {
                        //阶梯核验
                        //核验已有记录，与之前区间，不可相同
                        //匹配最后一个即可
                        $tmpl_config = $configs[count($configs) - 1];
                        if ($config['start_money'] < $tmpl_config['end_money']) {
                            return json(['code' => 0, 'msg' => '起始金额'.$config['start_money']."非有效阶梯设置"]);
                        }
                    }


                    $configs[] = $config;
                }

                $config = json_encode($configs);
            }

            Db::name('config')->where([['name','=','admin_setticheng_config'],['inc_type','=','setticheng']])->update(['value'=>$config]);
            return json(['code' => 1, 'msg' => '提成设置成功!', 'url' => myurl('auth/adminSetticheng')]);
        }else{
            $setticheng = Db::name('config')->where([['name','=','admin_setticheng_config'],['inc_type','=','setticheng']])->find();
            $info = '';
            $count = 0;
            if (!empty($setticheng['value'])) {
                $info = json_decode($setticheng['value'],true);
                $count = count($info);
            }
            View::assign('info', $info);
            View::assign('count', $count);
            View::assign('title','提成点设置');
            return view('adminSetticheng');
        }
    }

    /*-----------------------用户组管理----------------------*/
    //用户组管理
    public function adminGroup(){
        if($this->request->isPost()){
            $list = AuthGroup::select()->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1]);
        }
        return view();
    }
    //删除管理员分组
    public function groupDel(){
        $id=input('id',0,'intval');
        if($id==1){
            return json(['code'=>0,'msg'=>'系统自带用户组无法删除!']);
        }
        AuthGroup::where('id','=',$id)->delete();
        return json(['code'=>1,'msg'=>'删除成功!']);
    }
    //添加分组
    public function groupAdd(){
        if($this->request->isPost()){
            $data=$this->request->post();
            if(empty($data['title'])){
                $this->error('用户组名提交不能为空！');
            }
            $group_id=Db::name('auth_group')->where('title','=',$data['title'])->value('id');
            if($group_id){
                $this->error('用户组名已存在，保存失败！');
            }
            $data['addtime']=time();
            Db::name('auth_group')->strict(false)->insert($data);
            $this->success('用户组添加成功!',myurl('adminGroup'));
        }else{
            $authGroup = Db::name('auth_group')->field('id AS id,pid,title')->order('pid asc,id asc')->select();
            $nav = new Leftnav();
            $authGroupTree = $nav->menu($authGroup);
            View::assign('authGroupTree',$authGroupTree);

            View::assign('title','添加用户组');
            View::assign('info','null');
            View::assign('info_raw',[]);
            return View::fetch('groupForm');
        }
    }
    //修改分组
    public function groupEdit(){
        if($this->request->isPost()) {
            $data=$this->request->post();
            if(empty($data['title'])){
                $this->error('用户组名提交不能为空！');
            }
            $group_id=Db::name('auth_group')->where('title','=',$data['title'])->where('id','<>',$data['id'])->value('id');
            if($group_id){
                $this->error('用户组名已存在，保存失败！');
            }
            Db::name('auth_group')
                ->where('group_id','=',$data['group_id'])
                ->update($data);
            $this->success('用户组修改成功!',myurl('adminGroup'));
        }else{
            $authGroup = Db::name('auth_group')->field('group_id AS id,pid,title')->order('pid asc,group_id asc')->select();
            $nav = new Leftnav();
            $authGroupTree = $nav->menu($authGroup);
            View::assign('authGroupTree',$authGroupTree);
            $id = input('id');
            $info=Db::name('auth_group')->where('group_id','=',$id)->find();
            View::assign('info', json_encode($info,true));
            View::assign('info_raw', $info);
            View::assign('title','编辑用户组');
            return View::fetch('groupForm');
        }
    }
    //分组配置规则
    public function groupAccess(){
        $nav = new Leftnav();
        $admin_rule=\think\facade\Db::name('auth_rule')->field('id,pid,title')->order('sort asc')->select();
        $rules = \think\facade\Db::name('auth_group')->where('id',input('id'))->value('rules');
        $arr = $nav->auth($admin_rule,$pid=0,$rules);
        $arr[] = [ "id"=>0,
            "pid"=>0,
            "title"=>"全部",
            "open"=>true];
        View::assign('data',json_encode($arr,true));
        $this->app->view->engine()->layout(false);
        return View::fetch();
    }
    public function groupSetaccess(){
        $rules = input('post.rules');
        if(empty($rules)){
            return json(['msg'=>'请选择权限!','code'=>0]);
        }
        $data = $this->request->post();
        $where['id'] = $data['id'];
        unset($data['id']);
        if(AuthGroup::update($data,$where)){
            Cache::clear();
            return json(['msg'=>'权限配置成功!','url'=>myurl('auth.group/index'),'code'=>1]);
        }else{
            return json(['msg'=>'保存错误','code'=>0]);
        }
    }

    /********************************权限管理*******************************/
    public function adminRule(){
        if($this->request->isPost()){
            $arr = cache('authRuleList');
            if(!$arr){
				$arr = Db::name('authRule')->order('pid asc,sort asc')->select()->toArray();
				foreach($arr as $k=>$v){
                    $arr[$k]['lay_is_open']=false;
                }
                cache('authRuleList', $arr, 3600);
            }
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$arr,'is'=>true,'tip'=>'操作成功']);
        }
        return view();
    }
    public function clear(){
        $arr = Db::name('authRule')->where('pid','<>',0)->select();
        foreach ($arr as $k=>$v){
            $p = Db::name('authRule')->where('id',$v['pid'])->find();
            if(!$p){
                Db::name('authRule')->where('id',$v['id'])->delete();
            }
        }
        Cache::clear();
        $this->success('清除成功');
    }
    public function ruleAdd(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $data['addtime'] = time();
            authRule::create($data);
            Cache::clear();
            return json(['code'=>1,'msg'=>'权限添加成功!','url'=>myurl('adminRule')]);
        }else{

            $arr = cache('addAuthRuleList');

            if(!$arr){
                $authRule = Db::name('authRule')->order('pid asc,sort asc')->select();
                $nav = new Leftnav();
                $arr = $nav->menu($authRule);
                cache('addAuthRuleList', $arr, 3600);
            }
            $this->app->view->engine()->layout(false);
            View::assign('admin_rule',$arr);//权限列表
            return View::fetch();
        }
    }
    public function ruleOrder(){
        $auth_rule=\think\facade\Db::name('auth_rule');
        $data = $this->request->post();
        if($auth_rule->update($data)!==false){
            Cache::clear();
            return json(['code'=>1,'msg'=>'排序更新成功!','url'=>myurl('adminRule')]);
        }else{
            return json(['code'=>0,'msg'=>'排序更新失败!']);
        }
    }
    //设置权限菜单显示或者隐藏
    public function ruleState(){
        $id=input('post.id');
        $menustatus=input('post.menustatus');
        if(Db::name('auth_rule')->where('id='.$id)->update(['menustatus'=>$menustatus])!==false){
            Cache::clear();
            return json(['status'=>1,'msg'=>'设置成功!']);
        }else{
            return json(['status'=>0,'msg'=>'设置失败!']);
        }
    }
    //设置权限是否验证
    public function ruleTz(){
        $id=input('post.id');
        $authopen=input('post.authopen');
        if(Db::name('auth_rule')->where('id='.$id)->update(['authopen'=>$authopen])!==false){
            Cache::clear();
            return json(['status'=>1,'msg'=>'设置成功!']);
        }else{
            return json(['status'=>0,'msg'=>'设置失败!']);
        }
    }
    public function ruleDel(){
        authRule::destroy(['id'=>input('get.id')]);
        Cache::clear();
        return json(['code'=>1,'msg'=>'删除成功!']);
    }

    public function ruleEdit(){
        if($this->request->isPost()) {
            $datas = $this->request->post();
            if(authRule::update($datas)) {
                Cache::clear();
                return json(['code' => 1, 'msg' => '保存成功!', 'url' => myurl('adminRule')]);
            } else {
                return json(['code' => 0, 'msg' =>'保存失败！']);
            }
        }else{
            $arr = cache('addAuthRuleList');

            if(!$arr){
                $authRule = Db::name('authRule')->order('pid asc,sort asc')->select();
                $nav = new Leftnav();
                $arr = $nav->menu($authRule);
                cache('addAuthRuleList', $arr, 3600);
            }
            View::assign('admin_rule',$arr);//权限列表

            $admin_rule=Db::name('auth_rule')->where('id','=',input('id'))->find();
            View::assign('rule',$admin_rule);
            $this->app->view->engine()->layout(false);
            return View::fetch();
        }
    }

}
